package org.study.solr.boot.util;

import com.alibaba.fastjson2.*;
import com.google.common.collect.Lists;
import lombok.*;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * 使用 Java 解析 HTML
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2022年09月27日
 */
public class ProductUtils {
    public static void main(String[] args) {
        String keyWord = "iPhone";
        List<TaoBaoProduct> taobao = taobao(keyWord);
        List<JdProduct> jd = jd(keyWord);
        List<SuningProduct> suning = suning(keyWord, 5);
        System.out.println("");
    }

    public static List<TaoBaoProduct> taobao(String keyWord) {
        List<TaoBaoProduct> list = Lists.newArrayList();
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            String url = "https://odin.re.taobao.com/search_tbuad?=true&page=1&count=100000&pid=430672_1006&elemtid=1&reqFields=eurl%2CimgUrl%2Cismall%2CitemId%2Cloc%2Cprice%2CsellCount%2CpromoPrice%2CpromoName%2CsellerPayPostfee%2Ctitle%2CdsrDeliver%2CdsrDescribe%2CdsrService%2CdsrDescribeGap%2CdsrServiceGap%2CdsrDeliverGap%2CspGoldMedal%2Cisju%2CpriceDiscount%2CwangwangId%2Credkeys&keyword=" + keyWord;
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.102 Safari/537.36 OPR/90.0.4480.84");
            CloseableHttpResponse response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String json = EntityUtils.toString(entity, Consts.UTF_8);
                JSONObject jsonObject = JSON.parseObject(json);
                JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("data1");
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject p = (JSONObject) jsonArray.get(i);
                    JSONArray redkeysJSONArray = JSONArray.parse(p.getString("redkeys"));
                    TaoBaoProduct taoBaoProduct = TaoBaoProduct.builder().loc(p.getString("loc")).isju(p.getInteger("isju")).eurl(p.getString("eurl")).sellerPayPostfee(p.getBoolean("sellerPayPostfee")).ismall(p.getInteger("ismall")).title(p.getString("title")).wangwangId(p.getString("wangwangId")).imgUrl(p.getString("imgUrl")).itemId(p.getLong("itemId")).price(p.getBigDecimal("price")).redkeys(redkeysJSONArray.toList(String.class)).sellCount(p.getInteger("sellCount")).build();
                    list.add(taoBaoProduct);
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static List<JdProduct> jd(String keyWord) {
        List<JdProduct> list = Lists.newArrayList();
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            String url = "https://search.jd.com/Search?enc=utf-8&keyword=" + keyWord;
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.102 Safari/537.36 OPR/90.0.4480.84");
            CloseableHttpResponse response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String html = EntityUtils.toString(entity, Consts.UTF_8);
                Document doc = Jsoup.parse(html);
                Elements products = doc.select("ul[class='gl-warp clearfix'] > li");
                for (int i = 0; i < products.size(); i++) {
                    Element li = products.get(i);
                    String skuId = li.attr("data-sku");
                    String productName = li.select("div[class='p-name p-name-type-2']").select("em").text().replace("<font class=\"skcolor_ljg\">", "").replace("</font>", "");
                    String detailPage = "https:" + li.select("div[class='p-img']").select("a").attr("href");
                    String imgUrl = "https:" + li.select("div[class='p-img']").select("img").attr("data-lazy-img");
                    String price = li.select("div[class='p-price']").select("i").text();
                    String shopName = li.select("div[class='p-shop']").select("a").text();
                    String goodsType = li.select("div[class='p-icons']").select("i").text();
                    String province = li.select("div[class='p-stock hide']").attr("data-province");
                    JdProduct jdProduct = JdProduct.builder().skuId(Long.valueOf(skuId)).productName(productName).detailPage(detailPage).imgUrl(imgUrl).price(price).shopName(shopName).goodsType(goodsType).province(province).build();
                    list.add(jdProduct);
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static List<SuningProduct> suning(String keyWord, int totalPage) {
        List<SuningProduct> list = Lists.newArrayList();
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            for (int page = 1; page <= totalPage; page++) {
                String url = "https://search.suning.com/emall/searchV1Product.do?pg=01&paging=" + page + "&keyword=" + keyWord;
                HttpGet httpGet = new HttpGet(url);
                httpGet.setHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.102 Safari/537.36 OPR/90.0.4480.84");
                CloseableHttpResponse response = httpclient.execute(httpGet);
                HttpEntity entity = response.getEntity();
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    String html = EntityUtils.toString(entity, Consts.UTF_8);
                    Document doc = Jsoup.parse(html);
                    Elements products = doc.select("li");
                    for (int i = 0; i < products.size(); i++) {
                        Element li = products.get(i);
                        String skuId = li.attr("id").split("-")[1];
                        String productName = li.select("div[class='img-block']").select("a").attr("title");
                        String detailPage = "https:" + li.select("div[class='img-block']").select("a").attr("href");
                        String imgUrl = "https:" + li.select("div[class='img-block']").select("img").attr("src");
                        String price = "0";
                        String shopName = li.select("div[class='store-stock']").select("a").text();
                        SuningProduct suningProduct = SuningProduct.builder().skuId(Long.valueOf(skuId)).productName(productName).detailPage(detailPage).imgUrl(imgUrl).price(price).shopName(shopName).build();
                        list.add(suningProduct);
                    }
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    static class TaoBaoProduct {
        private String loc;
        private Integer isju;
        private String eurl;
        private Boolean sellerPayPostfee;
        private Integer ismall;
        private String title;
        private String wangwangId;
        private String imgUrl;
        private Long itemId;
        private BigDecimal price;
        private List<String> redkeys;
        private Integer sellCount;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    static class JdProduct {
        private Long skuId;
        private String productName;
        private String detailPage;
        private String imgUrl;
        private String price;
        private String shopName;
        private String goodsType;
        private String province;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    static class SuningProduct {
        private Long skuId;
        private String productName;
        private String detailPage;
        private String imgUrl;
        private String price;
        private String shopName;
    }
}
